<?php

namespace App\Http\Controllers\V1\Api;

use App\Jobs\SendCollectDataPushJob;
use App\Models\V1\BasicCircuits;
use App\Models\V1\BasicCollectors;
use App\Models\V1\BasicCollectTransformers;
use App\Models\V1\BasicTransformers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Http\Response;
use Validator;
use JPush\Client as JPush;
use Log;

class CollectDataController extends BaseController
{
    /****
     * 采集器发送采集的数据
     * @param Request $request
     */
    public function collectData(Request $request) {
        // 自定义返回格式
        $result = array(
            'errorCode' => Response::HTTP_NOT_FOUND,
            'errorMsg' => Response::$statusTexts[Response::HTTP_NOT_FOUND],
            'data' => array()
        );

        $error = $this->validateData($request,$result);
        if (!empty($error) || isset($error)) {
            $result = $error;
            return $this->sendResponse($result, $result['errorCode']);
        }

        $mac_code = $request->get('mac_code');
        $name = $request->get('name');
        $temperature = empty($request->get('temperature')) ? NULL : $request->get('temperature') ;
        $voltage = empty($request->get('voltage')) ? NULL : $request->get('voltage');
        $electric = empty($request->get('electric')) ? NULL : $request->get('electric');

        if ($request->method() === 'POST') {
            // 根据mac_code获取采集器的代码
            $collector = BasicCollectors::where('mac_code',$mac_code)->first();
            // 判断回路在回路表中是否存在，如果该采集器下该回路名不存在则插入
            $collector_code = $collector['code'];
            $circuitObj = BasicCircuits::where(['collector_code'=>$collector_code,'name'=>$name])->first();
            $circuit_code = empty($circuitObj) ? 'CIT'.uniqid() : $circuitObj['code'];
            //插入数据
            if (empty($circuitObj)){
                $insert_data = [
                    'code' => $circuit_code,
                    'name' => $name,
                    'collector_code' => $collector_code,
                ];
                BasicCircuits::create($insert_data);

            }
            $data = new BasicCollectTransformers;
            $data->code = 'CTSR'.uniqid();
            $data->circuit_code = $circuit_code;
            $data->temperature = $temperature;
            $data->voltage = $voltage;
            $data->electric = $electric;
            if ($data->save()) {
                // 判断是否要推送
                if ($temperature > 40 || $voltage > 30 || $electric > 20){
                    Log::info('推送啦');
                    // 推送
                    $flag = $this->sendPush($mac_code);
                    Log::info('$flag',['a'=>$flag]);
                    if ($flag){
                        $result['errorCode'] = Response::HTTP_OK;
                        $result['errorMsg'] = '推送成功';
                        return $this->sendResponse($result,$result['errorCode']);
                    }

                }
                $result['errorCode'] = Response::HTTP_OK;
                $result['errorMsg'] = Response::$statusTexts[Response::HTTP_OK];
            }
        }

        return $this->sendResponse($result,$result['errorCode']);
    }

    /***
     * 验证参数
     * @param Request $request
     * @return mixed
     */
    public function validateData(Request $request,Array $result)
    {
        //校验规则
        $rules = array();
        $rules['mac_code'] = 'bail|required|exists:basic_collectors,mac_code,deleted_at,NULL';
        //错误提示信息
        $messages = array();
        $messages['mac_code.required'] = '采集器编号不能为空';
        $messages['mac_code.exists'] = '采集器编号不存在';

        $validator = Validator::make($request->all(),$rules,$messages);  //第一个参数是提交的数据，第二个是校对规则，第三个是错误信息
        $errors = $validator->errors()->all(); //这是捕获到的所有参数验证的错误信息
        if(!empty($errors)) {
            $first_errors = $errors[0];
            $result['errorCode'] = Response::HTTP_BAD_REQUEST;
            $result['errorMsg'] = $first_errors;
            return $result;
        }
    }

    public function sendPush($code)
    {
        $successFlag = false;
        // 根据mac_code获取采集器的代码
        $collector = BasicCollectors::where('mac_code',$code)->first();
        if ($collector){
            $transformer_code = $collector['transformer_code'];
            // 根据采集器的代码code获取变压器的信息
            $transformer = BasicTransformers::where('code',$transformer_code)->first();
            if ($transformer){
                //变压器所属的客户
                $customer = $transformer->customer;
                $customer_name = $customer['name'];
                $transformer_model_code = $transformer['model_code'];
                $transformer_address = $transformer['address'];
                $ids = ['admin','ma001'];

                $data = array(
                    'userIds' => $ids,
                    'customer_name' => $customer_name,
                    'transformer_model_code' => $transformer_model_code,
                    'address' => $transformer_address,
                    'type' => '1' //采集数据
                );
                //创建任务实例，并分发任务
                $this->dispatch(new SendCollectDataPushJob($data));

                $successFlag = true;
                return $successFlag;
            }

        }
        return $successFlag;
    }
}
